#!/bin/sh

ACTION="$1"
MAC="$2"
IP="$3"
IS_EXIST=`arptables -nvL|grep -nr $MAC`
STATIC_FILE="/etc/ethers"
INPUT_STATIC_LEASE_CHAIN="STATIC_LEASE_INPUT"
STATIC_LEASE_CMD_FILE="/tmp/arptables_staticlease"
input_chain_exist=""
staticip=""

#arptables -P INPUT ACCEPT
if [ "$ACTION" = "add" ];then
	[ "$IS_EXIST" == "" ] && {
		/usr/sbin/arptables -I INPUT --src-ip $IP --src-mac ! $MAC -j DROP
	}
elif [ "$ACTION" = "del" ];then
	/usr/sbin/arptables -D INPUT --src-ip $IP --src-mac ! $MAC -j DROP
else
	echo "$ACTION, $MAC, $3, $4, $5, $6, $7" > /dev/null
fi

input_chain_exist=`arptables -nvL | grep "\-j $INPUT_STATIC_LEASE_CHAIN"`
echo "#auto generated by /etc/dhcplease.script#" > $STATIC_LEASE_CMD_FILE
if [ -z "$input_chain_exist" ]; then                           
	echo "arptables -N $INPUT_STATIC_LEASE_CHAIN" >> $STATIC_LEASE_CMD_FILE
	echo "arptables -A INPUT -j $INPUT_STATIC_LEASE_CHAIN" >> $STATIC_LEASE_CMD_FILE
else                                                                     
	echo "arptables -F $INPUT_STATIC_LEASE_CHAIN" >> $STATIC_LEASE_CMD_FILE
fi                                                                                      
                                                                                                 
enable_static_lease=`uci -q get dhcp.@dnsmasq[0].readethers`
if [ -e "$STATIC_FILE" ] && [ "$enable_static_lease" == "1" ];then                                      
	IFS_old=$IFS
	IFS=$'\n'
	for  staticip  in  `cat $STATIC_FILE`                                          
	do
		MAC=`echo "$staticip"|cut -d ' ' -f 1`                            
		IP=`echo "$staticip"|cut -d ' ' -f 2`
		#echo "macaddr:$MAC" > /dev/console
		[ -n $MAC ] && [ -n $IP ] && {
			echo "arptables -A $INPUT_STATIC_LEASE_CHAIN --src-ip $IP --src-mac ! $MAC -j DROP" >> $STATIC_LEASE_CMD_FILE
		}                         
	done 
	IFS=$IFS_old                                                                  
fi 
sh $STATIC_LEASE_CMD_FILE
